﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Objects;

namespace App.Domain
{
    public partial class AppEntities
    {
        private static List<String> _historyMembers = new List<string> { "ProductVisitDetails", "Product" };
        public static List<String> HistoryMembers
        {
            get { return _historyMembers; }
            set { _historyMembers = value; }
        }
        public int UserID { get; set; }

        partial void OnContextCreated()
        {
            this.SavingChanges += new EventHandler(AppEntities_SavingChanges);
        }

        void AppEntities_SavingChanges(object sender, EventArgs e)
        {
            var modifiedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted);
            foreach (var entry in modifiedEntities)
            {
                if (HistoryMembers.Contains(entry.EntityKey.EntitySetName))
                {
                    //IEnumerable<ObjectStateEntry> addedProperties = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).Get
                    int? userID = getApplicationUserID();                    
                    if (entry.State == EntityState.Added)
                    {

                    }
                    if (entry.State == EntityState.Modified)
                    {
                        var modifiedProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();
                        var currentValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues;
                        foreach (var propName in modifiedProps)
                        {
                            var newValue = currentValues[propName];
                            //log changes
                        }
                    }                    
                }
            }
        }

        private int? getApplicationUserID()
        {
            //if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Session != null)
            //{
            //    System.Web.HttpContext.Current.Session["CURRENT_USER"] UserViewModel
            //}
            return null;
        }
    }
}
